package com.sjgs.gis.service;

import com.sjgs.gis.domain.DataFile;
import com.sjgs.gis.repository.DataFileRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;


@Service
public class DataFileService {

    private final DataFileRepository repository;

    public DataFileService(DataFileRepository repository) {
        this.repository = repository;
    }

    public Flux<DataFile> findAll() {
        return repository.findAll();
    }

    public Flux<DataFile> findByFileName(String fname) {
        return repository.findAllByFkeyEndsWith(fname);
    }

    public Mono<DataFile> findByFkeyAndStatusGreaterThan(String fkey, Integer status) {
        return repository.findByFkeyAndStatusGreaterThan(fkey, status);
    }

    public Mono<DataFile> findByFkeyAndStatusLessThanEqual(String fkey, Integer status){
        return repository.findByFkeyAndStatusLessThanEqual(fkey, status);
    }

    public Mono<DataFile> findByFkey(String fkey) {
        return this.repository.findByFkey(fkey);
    }


    public Mono<DataFile> findByFkeyAndStatus(String fkey, Integer status) {
        return repository.findByFkeyAndStatus(fkey, status);
    }

    public Mono<DataFile> save(DataFile datafile) {
        return repository.save(datafile);
    }


    public Mono<Void> delete(DataFile datafile) {
        return repository.delete(datafile);
    }

    @Transactional
    public Mono<DataFile> insertOrUpdate(DataFile datafile) {
        return repository.findAllByFkey(datafile.getFkey())
                .collectList()
                .flatMap(list -> {
                    if (list.size() > 0) {
                        DataFile df = list.get(0);
                        datafile.setId(df.getId());
                        datafile.setUpdateTime(LocalDateTime.now());
                        return save(datafile);
                    } else {
                        datafile.setPutTime(LocalDateTime.now());
                        return save(datafile);
                    }
                });
    }
}
